import * as glob from 'glob';
import { } from '';
const Task = require('data.task');
const { chain, fold, I, map, ap } = require('pointfree-fantasy');
const Maybe = require('data.maybe');
const { view, lensPath, __, lensProp, filter, propEq, prop, fromPairs, uniq, isEmpty, curry, isNil, not, pipe, tap, apply, compose, flip, forEach, merge, ifElse, concat, mergeAll, reduce, keys } = require('ramda');
const bluebirdPromise = require('bluebird');

const loadFiles = (pattern: string, ignores: string[]) =>
    new Task((rej, res) => glob(pattern, ignores, (err, files) => {
        if (err) rej(err)
        else res(files)
    }))

interface IFullResError {
    message?: string;
    i18nMsg?: string;
    code?: number;
    data?: any;
    stack?: any;
}

interface IResError {
    code?: number;
    error?: any;
}

function errorFactory(obj: IFullResError): IResError {
    const result: any = {};
    result.code = obj.code;
    result.error = new Error(obj.message); // error instance
    result.error.i18nMsg = obj.i18nMsg; // for i18n
    result.error.data = obj.data || null;
    return result;
}

const rejectNull = curry((rejection, x: any) => x == null
    ? new Task(rej => rej(rejection))
    : new Task((rej, res) => res(x)));

const rejectNotNull = curry((rejection, x: any) => x != null
    ? new Task(rej => rej(rejection))
    : new Task((rej, res) => res(x)));

const renameKeys = curry((keysMap, obj) => {
    return reduce((acc, key) => {
        acc[keysMap[key] || key] = obj[key];
        return acc;
    }, {}, keys(obj));
});

export {
    loadFiles,
    errorFactory,
    rejectNull,
    rejectNotNull,
    renameKeys
}